package com.zhentao.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


import com.zhentao.loginUser.pojo.TMenu;
import com.zhentao.loginUser.pojo.TRole;
import com.zhentao.mapper.TMenuMapper;
import com.zhentao.pojo.TUser;
import com.zhentao.service.TMenuService;
import com.zhentao.service.TUserService;
import com.zhentao.mapper.TUserMapper;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
* @author song-xinhang
* @description 针对表【t_user】的数据库操作Service实现
* @createDate 2024-07-20 08:44:57
*/
@Service
@Slf4j
@Api
public class TUserServiceImpl extends ServiceImpl<TUserMapper, TUser>
    implements TUserService, UserDetailsService {
    @Resource
    private TUserMapper tUserMapper;
    @Resource
    private TMenuMapper tMenuMapper;
    @Resource
    private TMenuService tMenuService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        LambdaQueryWrapper<TUser> queryWrapper = Wrappers.<TUser>lambdaQuery().eq(TUser::getUsername, username);
        TUser tUser = tUserMapper.selectOne(queryWrapper);
        if (tUser == null) {
            throw new UsernameNotFoundException("用户 " + username + " 未找到");
        }
        // 查询权限
        List<String> perms = tMenuMapper.getLimitsOfAuthority(tUser.getUserId());
        if (perms == null) {
            perms = new ArrayList<>();
        }
        tUser.setPerms(perms);
        // 查询角色
        TRole roles = tUserMapper.getRoleList(tUser.getUserId());
        if (roles == null) {
            roles = new TRole();
        }
        tUser.setRoles(roles);
        // 动态菜单查询
        List<TMenu> menus = tMenuMapper.getDynamicMenu(roles.getRoleId());
        if (menus == null) {
            menus = new ArrayList<>();
        }
        for (TMenu menu : menus) {
            List<TMenu> list = tMenuService.list(Wrappers.<TMenu>lambdaQuery().eq(TMenu::getParentId, menu.getMenuId()));
            if (list == null) {
                list = new ArrayList<>();
            }
            menu.setMenus(list);
        }
        tUser.setMenus(menus);
        log.info("one==============>{}", tUser);
        return tUser;
    }

    @Override
    public List<TMenu> findLoginTMenu(Integer uid) {
        List<TMenu> loginTMenu = tUserMapper.findLoginTMenu(uid);
        return loginTMenu;
    }
}




